﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    public class WStest
    {
        public void WStestFunc()
        {
            ws1.WebService1SoapClient ws = new ws1.WebService1SoapClient();
            //SimpleWS(ws);
            //AsyncWS(ws);
            //AsyncWS2(ws);
            //AsyncWS3(ws);

            //WS缓存
            WSCacheTest(ws);
        }

        #region 调用方式
        private void SimpleWS(ws1.WebService1SoapClient ws)
        {
            //最简单的调用方式，添加服务引用后调用WS命名空间里的方法            
            Console.WriteLine(ws.HelloWorld());
            Console.WriteLine("普通调用");
        }

        private async void AsyncWS(ws1.WebService1SoapClient ws)
        {
            //异步调用，防止WS调用时间过长导致UI界面卡死
            Task<string> task = Task.Run(() =>
            {
                return ws.HelloWorld2();
            });
            Console.WriteLine("HelloWorld2之前还是之后呢");
            string result = await task;    //await会挂起主线程
            Console.WriteLine(task.Result);
        }

        private async void AsyncWS2(ws1.WebService1SoapClient ws)
        {
            //异步调用，防止WS调用时间过长导致UI界面卡死
            Task<string> task = Task.Run(() =>
            {
                return ws.HelloWorld2();
            });

            //不影响主线程
            task.GetAwaiter().OnCompleted(() =>
            {
                var result = task.Result;
                Console.WriteLine(result);
            });
            Console.WriteLine("HelloWorld2之前还是之后呢");
        }

        private async void AsyncWS3(ws1.WebService1SoapClient ws)
        {
            //异步调用，防止WS调用时间过长导致UI界面卡死
            var result = AsyncFunc(ws);
            Console.WriteLine("HelloWorld2之前还是之后呢");
            Console.WriteLine(result.Result);
        }
        private async Task<string> AsyncFunc(ws1.WebService1SoapClient ws)
        {
            return await Task.Run(() =>
            {
                return ws.HelloWorld2();
            });
        }

        #endregion
       

        private void WSCacheTest(ws1.WebService1SoapClient ws)
        {
            //测试结果，设置绝对过期时间，10秒内返回的时间都一样，10秒后重新缓存了新的时间
            //设置了可变过期时间，10秒内都一样，每2.5秒访问一次的话都是不同的数据(可变过期是最后访问的时期与可变过期的间隔)
            for (int i = 0; i < 10; i++)
            {
                Thread.Sleep(1000);
                Console.WriteLine(ws.CacheTest2());
            }

            for (int i = 0; i < 6; i++)
            {
                Thread.Sleep(2500);
                Console.WriteLine(ws.CacheTest2());
            }
            
        }

        
    }
}
